import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/global.dart';
import 'package:o2oa_all_platform/common/index.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

Future<void> main() async {
  await Global.init();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  // 主题模式  light dark
  ThemeMode mode = ThemeMode.system;
  // 主题
  ThemeData lightTheme = AppTheme.defaultLightTheme;
  ThemeData darkTheme = AppTheme.defaultDarkTheme;

  Locale? _locale = Languages.locale;
  bool needGrey = false;
  final _eventMsgId = 'MyApp';
  @override
  void initState() {
    // 是否需要全局黑白
    needGrey = SharedPreferenceService.to.getBool(
        SharedPreferenceService.appStyleNeedGreyKey,
        defaultValue: false);
    loadThemeMode();
    _locale = LanguageListExt.getCurrentLanguage().getLocale();
    // 监听黑白变化
    EventBus().on(EventBus.greyColorChangeGlobalMsg, _eventMsgId, (arg) {
      OLogger.d('接收到了 全局黑白的变化');
      changeGreyColor();
    });
    super.initState();
  }

  /// 全局黑白 或者 还原
  void changeGreyColor() {
    setState(() {
      needGrey = SharedPreferenceService.to.getBool(
          SharedPreferenceService.appStyleNeedGreyKey,
          defaultValue: false);
    });
  }

  /// 主题皮肤相关信息
  void loadThemeMode() {
    mode = SharedPreferenceService.to.getThemeMode();
    OLogger.d('当前系统主题mode： ${mode.name}');
    final skin = SharedPreferenceService.to.getThemeSkin();
    lightTheme = AppTheme.getLightThemeBySkin(skin);
    darkTheme = AppTheme.getDarkThemeBySkin(skin);
    OLogger.d('当前系统主题皮肤： ${skin.name}');
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    OLogger.d('页面根 MyApp build 。。。。。。。。。。。。');
    return O2UI.greyWidget(
        RefreshConfiguration(
          headerBuilder: () => const ClassicHeader(),
          footerBuilder: () => const ClassicFooter(),
          hideFooterWhenNotFull: true,
          headerTriggerDistance: 80,
          maxOverScrollExtent: 100,
          footerTriggerDistance: 150,
          child: OrientationBuilder(builder: (context, orientation) {
            final isPad = SharedPreferenceService.to
                .getBool(SharedPreferenceService.isPadKey);
            final screenWidth = MediaQuery.of(context).size.width;
            OLogger.d(
                'OrientationBuilder, orientation: $orientation isPad:$isPad screenWidth:$screenWidth');
            return isPad && orientation == Orientation.landscape
                ? blurBackground(screenWidth)
                : getMApp();
          }),
        ),
        needGrey);
  }

  Widget blurBackground(double screenWidth) {
    return Stack(alignment: Alignment.topLeft, children: [
      const Positioned.fill(
        child: AssetsImageView(
          'launch_background.png',
          fit: BoxFit.fill,
        ),
      ),
      Positioned.fill(
        child: BackdropFilter(
            filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
            child: FractionallySizedBox(
              widthFactor: screenWidth < 750 ? 1.0 : 750 / screenWidth,
              child: getMApp(),
            )),
      )
    ]);
  }

  GetMaterialApp getMApp() {
    return GetMaterialApp(
      title: 'appName'.tr,
      enableLog: true,
      themeMode: mode,
      theme: lightTheme, // 亮色主题
      darkTheme: darkTheme, // 暗色主题
      logWriterCallback: OLogger.writeFromGetx,
      defaultTransition: Transition.fade,
      initialRoute: O2OARoutes.splash,
      getPages: O2OAPages.pages,
      unknownRoute: O2OAPages.unknownRoute,
      // loading插件
      builder: EasyLoading.init(),
      // 多语言
      locale: _locale,
      fallbackLocale: Languages.fallbackLocale,
      translations: Languages(),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        RefreshLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('zh', 'CN'),
        Locale('en', 'US'),
        Locale('zh', 'HK'),
        Locale('es', 'ES'),
      ],
    );
  }
}
